<?php

class Controller {
	public $objRetorno;
	
	public function __construct(){
		
		$this->objRetorno['head'] 	= Config::$TEMPLATE.'/site/head';
		$this->objRetorno['pagina'] = Config::$TEMPLATE.'/site/conteudo';
		$this->objRetorno['footer'] = Config::$TEMPLATE.'/site/footer';
		
	}
    public static function exec() {
    	
        $class = Uri::getClass();
        $method = Uri::getMethod();

        $action = new $class;
        
        if(Security::checkAccess($class, $method)){
        	$action->$method();
        }else{
        	$securityClass = isset(Security::getObjSecurity()[$class][$method]['class']) ? Security::getObjSecurity()[$class][$method]['class'] : Security::getUrlSecurityClass();
        	$securityMethod = isset(Security::getObjSecurity()[$class][$method]['method']) ? Security::getObjSecurity()[$class][$method]['method'] : Security::getUrlSecurityMethod();
        	//echo '<meta http-equiv="refresh" content="0; url='.$url.'">';
        	Redirect::location($securityClass, $securityMethod);
        }
    }

    /**
     * Renderiza o template, view, ou valor fornecido.
     * @param string $templateOrView Nome do template ou view.
     * @param array $bindings Array que contem os bindings para o template.
     */
    public static function render($templateOrView, $bindings = NULL, $return = FALSE) {

        if ($templateOrView === "json") {

            OutputFormatter::convert($bindings);

            return;
        }

        if ($bindings != NULL) {
            foreach ($bindings as $key => $value) {
                $$key = $value;
            }
        }

        $path = "app/view/" . $templateOrView . ".phtml";


        if (file_exists($path)) {
            ob_start();
            include $path;
            $templateOrView = ob_get_contents();
            ob_get_clean();
        }


        if ($bindings != NULL) {
            $mustache = new Mustache();
            if ($return) {
                return $mustache->render($templateOrView, $bindings);
            }
            echo $mustache->render($templateOrView, $bindings);
        } else {
            if ($return) {
                return $templateOrView;
            }
            echo $templateOrView;
        }
    }

}

?>